<script setup lang="tsx">
import { computed, h, reactive, ref, watch } from 'vue';
import type { SelectGroupOption, SelectOption } from 'naive-ui/es/select/src/interface';
import type { SelectRenderLabel } from 'naive-ui';
import { NButton } from 'naive-ui';
import type { Type } from 'naive-ui/es/button/src/interface';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { Dict } from '@/service/api';
import { createDict, updateDict } from '@/service/api';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'DictOperateModal'
});

export type OperateType = NaiveUI.TableOperateType;

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Dict | null;
  /** 字典类型 */
  dictType: string;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.dict.addDict'),
    edit: $t('page.manage.dict.editDict')
  };
  return titles[props.operateType];
});

type Model = Pick<Dict, 'dictType' | 'label' | 'value' | 'colorType' | 'cssClass' | 'sort' | 'remark' | 'status'> & {
  id: number | null;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: null,
    dictType: '',
    label: '',
    value: '',
    colorType: null,
    cssClass: '',
    sort: 0,
    remark: '',
    status: 1
  };
}

type RuleKey = Extract<keyof Model, 'label' | 'status' | 'value' | 'sort'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  label: defaultRequiredRule,
  value: defaultRequiredRule,
  sort: defaultRequiredRule,
  status: defaultRequiredRule
};

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    // request
    const { error } = await updateDict(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createDict(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  model.dictType = props.dictType;

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

// 数据标签回显样式
const colorTypeOptions: Array<SelectOption | SelectGroupOption> = [
  {
    value: 'default',
    label: $t('common.colorType.default')
  },
  {
    value: 'primary',
    label: $t('common.colorType.primary')
  },
  {
    value: 'tertiary',
    label: $t('common.colorType.tertiary')
  },
  {
    value: 'success',
    label: $t('common.colorType.success')
  },
  {
    value: 'info',
    label: $t('common.colorType.info')
  },
  {
    value: 'warning',
    label: $t('common.colorType.warning')
  },
  {
    value: 'error',
    label: $t('common.colorType.error')
  }
];

const colorTypeRenderLabel: SelectRenderLabel = option => {
  return h(
    'div',
    {
      style: {
        display: 'flex',
        alignItems: 'center'
      }
    },
    [
      h(
        NButton,
        {
          type: option.value as Type,
          size: 'small',
          strong: true,
          secondary: true,
          style: {
            width: '100px'
          }
        },
        {
          default: () => option.value
        }
      ),
      h(
        NButton,
        {
          type: option.value as Type,
          size: 'small',
          ghost: true,
          style: {
            marginLeft: '12px'
          }
        },
        {
          default: () => option.label
        }
      )
    ]
  );
};
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" :mask-closable="false" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.manage.dict.dictType')" path="dictType">
          <NInput v-model:value="model.dictType" :placeholder="$t('page.manage.dict.form.dictType')" disabled />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.label')" path="label">
          <NInput v-model:value="model.label" :placeholder="$t('page.manage.dict.form.label')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.value')" path="value">
          <NInput v-model:value="model.value" :placeholder="$t('page.manage.dict.form.value')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.sort')" path="sort">
          <NInputNumber v-model:value="model.sort" :placeholder="$t('page.manage.dict.form.sort')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.status')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.colorType')" path="colorType">
          <NSelect
            v-model:value="model.colorType"
            :placeholder="$t('page.manage.dict.form.colorType')"
            :options="colorTypeOptions"
            :render-label="colorTypeRenderLabel"
            clearable
          />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.cssClass')" path="cssClass">
          <NInput v-model:value="model.cssClass" :placeholder="$t('page.manage.dict.form.cssClass')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.dict.type.remark')" path="remark">
          <NInput v-model:value="model.remark" :placeholder="$t('page.manage.dict.type.form.remark')" type="textarea" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped>
.flex-end {
  display: flex;
  justify-content: flex-end;
}
</style>
